'use strict';

const fs = require('fs');
const path = require('path');

const Service = require('egg').Service;

class FileService extends Service {

  async save(file,extname) {
    var  fileInfo = await this.ctx.model.File.findOne({where:{file:file}});
    
    if(!fileInfo) { //首次添加，新增

        fileInfo = await this.ctx.model.File.create({file:file,extname:extname,used:0});

    } else {

        await fileInfo.increment('used');
    }


    //存储客户端内容
    const d = new Date();
    const createdAt = d.getFullYear()+'-'+(d.getMonth()+1)+'-'+d.getDate() + ' '+ d.getHours() +':'+ d.getMinutes() + ':' + d.getSeconds();
    const clientInfo = await this.ctx.model.ClientFile.create({file_id:fileInfo.id,created_at:createdAt});
    return clientInfo.id;
  }

  async delete(clientFileId,file){
    
    const clientFile = await this.ctx.model.ClientFile.findByPk(clientFileId);
    if( !clientFile ) {
      return false;
    }

    const fileId = clientFile.file_id;

    //删除客户文件
    await this.ctx.model.ClientFile.destroy({where: {id: clientFileId}});

    //减少文件使用索引
    const fileInfo = await this.ctx.model.File.findByPk(fileId);

    if(fileInfo && (fileInfo.file + fileInfo.extname) ==  path.basename(file) ) { //文件存在

      if(fileInfo.used == 1){ //最后一次使用，直接删除

        await this.ctx.model.File.destroy({where: {id: fileId}});

        //将原始文件销毁
        fs.unlinkSync(this.config.uploadDir + '/' + file);

      }else{

        await this.ctx.model.File.decrement('used',{where:{id:fileId}});

      }
    }
    
    return true;
  }

  async submit(clientFileId) {
    const fileInfo = await this.ctx.model.ClientFile.findByPk(clientFileId)
    await this.ctx.model.ClientFile.update({valid:1},{where:{id:clientFileId}});  //将文件修改为已确定使用
    await this.ctx.model.File.increment('used',{where:{id:fileInfo.file_id}})
  }
}

module.exports = FileService;
